#!/usr/bin/python
# -*- coding: UTF-8 -*-
import __init__
import time
import threading
import tkinter

from exceptions import *

lock = threading.RLock()

def edit_config():
    import os
    from gui_config import config
    config.load()
    os.startfile(config.file)

def start(event):
    global lock
    index = int(event.widget.curselection()[0])
    selected = event.widget.get(index)
    if selected in worker_thread.thread_dict:
        print(selected,"线程已启动过.")
    else:
        print('启动',selected)
        worker_thread.thread_dict.setdefault(selected,worker_thread(selected,lock)).start()

def auto_run(event):
    global lock
    from gui_config import config
    event.widget['text'] = "Running"
    thread_list = []
    config.load()
    for section in config.cf.sections():
        print(section)
        if section != 'backend':
            t = worker_thread(section,lock)
            thread_list.append(t)
    for t in thread_list:
        print(t)
        t.start()


class worker_thread(threading.Thread):
    """docstring for worker_thread"""

    thread_dict = {}

    def __init__(self, selected ,lock):
        super(worker_thread, self).__init__()
        self.selected = selected
        self.lock = lock
        self.setDaemon(True)

    def run(self):
        from gui_config import config
        backend = config.get("backend","url")
        worker_init_args = config.cf[self.selected]
        worker_class = getattr(__init__,worker_init_args["classname"])
        try:
            worker = worker_class(backend=backend,lock=self.lock,config_entity=worker_init_args)
            runtime = int(config.get("backend","runtime"))
            import itertools
            repeat = itertools.repeat(runtime,runtime) if runtime != 0 else itertools.repeat(runtime)
            for i,runtime in enumerate(repeat):
                print("{i}/{runtime}次运行".format(i=i,runtime=runtime))
                try:
                    worker.run()
                    print("完成任务")
                    time.sleep(10)
                except GetMonitorHwndException as e:
                    #获取不了模拟器句柄.需要手动操作
                    raise e
                except GetTicketException as e:
                    #向服务器获取任务时发生异常.需要检查网络
                    raise e
                except StartBankAppException as e:
                    #启动手机银行时触发的异常，需要人工确认情况
                    raise e
                except LoginException as e:
                    #银行登录异常
                    raise e
                except StopException as e:
                    raise e
                except Exception as e:
                    raise e
                finally:
                    worker.unBindWindow()
        except StopException as e:
            print("停止！",str(e))
        except Exception as e:
            raise e
        finally:
            print(self.selected,"线程中止")
            worker_thread.thread_dict.pop(self.selected)

